/*
 * @Description: 分盒按钮
 * @Author: Rfan
 * @Date: 2022-06-17 19:46:09
 * @LastEditTime: 2022-06-24 18:43:38
 */

import { useEffect, useMemo, useState } from 'react';
import { Button } from 'antd';
import { fetchArchivesByRule, IRuleSearchParams } from '@/api/archives/archives';
import type { ICoordinate } from '@/interfaces/global';
import { useLevelTableContext } from '@/components/LevelTable/contexts/LevelTableContext';
import PackBoxDialog from '@/components/LevelTable/componentes/dialogs/PackBoxDialog';
import { selectItemByKey } from '@/utils/list';

interface IPackBox {
  coordinate: ICoordinate;
  data: any;
  onSave: any;
}

const PackBox = (props: IPackBox) => {
  const { coordinate, data } = props;

  const { selectItems, baseInfo, list } = useLevelTableContext();

  // 弹窗展示状态
  const [visible, setVisible] = useState(false);
  // 选中文件、卷内文件对象
  const [selectObjs, setSelectObjs] = useState([]);
  // 选中文件、卷内文件对象
  const [isMgrByFile, setIsMgrByFile] = useState(false);

  useEffect(() => {
    if (visible) {
      const mgrMode = baseInfo.level === 1 && baseInfo.levelNum === 1;
      setIsMgrByFile(mgrMode);
      getFiles(mgrMode);
    }
  }, [visible]);

  const getFiles = (mgrMode: boolean) => {
    if (mgrMode) {
      setIsMgrByFile(selectItems.map((id: number) => selectItemByKey(id, list)));
    } else {
      const params: IRuleSearchParams = {
        coordinate: { ...coordinate, level: 1 },
        commonParams: baseInfo.param.commonParams,
        fieldName: 'up_level_id',
        fieldValueList: [data.row_id]
      };
      fetchArchivesByRule(params).then((res) => {
        const { data } = res;
        setSelectObjs(data);
      });
    }
  };

  return (
    <>
      <Button
        type="text"
        disabled={isMgrByFile ? false : selectItems.length !== 1}
        onClick={() => {
          setVisible(true);
        }}
      >
        分盒
      </Button>
      {useMemo(
        () => (
          <PackBoxDialog
            visible={visible}
            selectObjs={selectObjs}
            onClose={() => {
              setVisible(false);
            }}
          />
        ),
        [visible, selectObjs]
      )}
    </>
  );
};

export default PackBox;
